package action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import util.ApplicationContextUtil;
import basic.action.BasicAction;
import cache.MethodCacheInterceptor;

public class CacheAction extends BasicAction {
	private static final Log logger = LogFactory.getLog(CacheAction.class);

	public ActionForward showCache(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MethodCacheInterceptor mi = (MethodCacheInterceptor) ApplicationContextUtil
				.getBean("methodCacheInterceptor");
		Cache cache = mi.getCache();
		if (cache != null) {
			List<Element> list = new ArrayList<Element>();
			for (Object key : cache.getKeys()) {
				Element element = cache.get((Serializable) key);
				list.add(element);
			}
			request.setAttribute("caches", list);
		}
		return mapping.findForward("showCache");
	}

	public ActionForward removeCache(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MethodCacheInterceptor mi = (MethodCacheInterceptor) ApplicationContextUtil
				.getBean("methodCacheInterceptor");
		Cache cache = mi.getCache();
		String key = request.getParameter("key");
		if (cache != null) {
			logger.info("removing cache:"+key);
			cache.remove(key);
		}
		response.sendRedirect("cache.do?method=showCache");
		return null;
	}

}